public:
    // 从右往左遍历
    int lengthOfLastWord(string s) {
        if (s.length() == 0) return 0;

        int end = s.length() - 1;
        while (end >= 0 && s[end] == ' ') end--;
        if (end < 0) return 0;

        int start = end;
        while (start >= 0 && s[start] != ' ') start--;

        return end - start;
    }

    // 从左往右遍历
    int lengthOfLastWord(string s) {
        int ans = 0;
        int start = 0, end = 0;
        int n = s.length();

        while (end < n) {
            if (s[start] == ' ') {
                start++;
                end++;
            } else {
                while (end < n && s[end] != ' ') end++;
                ans = end - start;
                while (end < n && s[end] == ' ') end++;
                if (end < n && s[end] != ' ') {
                    start = end;
                }
            }
        }
        return ans;
    }